<template>
  <!-- 询价结果 -->
  <div class="inquiry-result">
    <div class="btns" style="padding:1em;margin-bottom:1em;background:#fff">
      <el-input v-model="searchForm.name"  placeholder="请输入项目名"></el-input>
      <el-date-picker
        v-model="searchForm.time"
        unlink-panels
        value-format="timestamp"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>
      <el-button style="margin-right: 6px" type="primary" icon="el-icon-search" size="small" @click="toSearch">查询</el-button>
    </div>
    <el-card shadow="never" style="margin-bottom: 1em">
      <div slot="header" class="index-md-title">
        <span><b>项目表</b><b style="float: right">单位：元</b></span>
      </div>
      <a-table
        class="status-table"
        :pagination="proTable.pagination"
        :data-source="proTable.data"
        size="small"
        :rowKey="record => record.id"
        :loading="proTable.loading"
        :customRow="rowClick"
        :row-class-name="tableRowClassName"
        :scroll="{x:1300, y:windowHeight-400}"
      >
        <!-- <a-table-column :width="30" ellipsis="true" key="completeStatus" title="终审" data-index="completeStatus" align="center">
          <template slot-scope="text">
            <span v-if="text === 0" style="color: #42b983">{{完成}}</span>
            <span v-if="text != 0" style="color: crimson">{{未完成}}</span>
          </template>
        </a-table-column> -->
        <a-table-column :width="100" ellipsis="true" key="name" title="项目名" data-index="name" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="proNo" title="编号" data-index="proNo" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="type" title="类型" data-index="type" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="origin" title="来源" data-index="origin" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="quotationTotalPrice" title="总报价(¥)" data-index="quotationTotalPrice" align="center">
          <template slot-scope="text">
            <span style="color: crimson">{{text}}</span>
          </template>
        </a-table-column>
        <a-table-column :width="100" ellipsis="true" key="proRate" title="利率" data-index="proRate" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="remark" title="备注" data-index="remark" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="operator" title="创建人" data-index="operator" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="time" title="创建时间" data-index="time" align="center"
          defaultSortOrder="descend"
          :sorter="(a, b)=>a.time-b.time"
        >
          <template slot-scope="text">{{dateTimeFormat(text)}}</template>
        </a-table-column>
      </a-table>
    </el-card>

    <el-drawer
      title="询价结果表"
      :visible.sync="drawer"
      direction="rtl"
      size="70%"
    >
      <el-card shadow="never">
      <div slot="header" class="index-md-title">
        <el-button type="primary" style="float: right" size="small" @click="batchUpdatePrice">批量修正报价</el-button>
        <div style="margin-left: 1em; display: inline-block">
          <span v-if="currentPro!='' && currentPro">【{{currentPro}}】</span>

        </div>
      </div>
      <div style="margin:4px">
          <el-button type="info" icon="el-icon-document" size="small" :loading="downloadLoading" @click="handleDownload">导出Excel</el-button>
          <el-button :disabled="selectedRowKeys.length>0? false: true" type="success" size="small" @click="toPurchase">发往采购</el-button>
          <el-button :disabled="selectedRowKeys.length>0? false: true" type="warning" size="small" @click="cancelPurchase">取消采购</el-button>
      </div>
      <div style="margin-top:4px">
        <a-table
          size="small"
          :rowKey="record => record.quoteId"
          :pagination="detailTable.pagination"
          :loading="detailTable.loading"
          :data-source="detailTable.data"
          :scroll="{x:1300, y:windowHeight-400}"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, selections: [{
              key: 'all-data',
              text: '全选',
              onSelect: allChange,
          }]}"
          @change="(p, f, s) => {
            handleTableChange(p, f, s, loadPurchases)
          }"
        >
        <a-table-column :width="80" align="center" title="状态" key="isPurchase" data-index="isPurchase">
          <template slot-scope="text">
            <el-tag v-if="text === 0 || text == null" type="info">无状态</el-tag>
            <el-tag v-else-if="text === 1" type="success">已发采购</el-tag>
            <el-tag v-if="text === 2" type="warning">取消采购</el-tag>
          </template>
        </a-table-column>
        <a-table-column defaultSortOrder="ascend" :sorter="true" title="序号" key="sort" data-index="sort" align="center" :width="50" />
        <a-table-column :width="100" ellipsis="true" key="name" title="名称" data-index="name" align="center"/>
        <a-table-column :width="100" ellipsis="true" :sorter="true" key="supplier" title="供应商" data-index="supplier" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="suBrand" title="品牌" data-index="suBrand" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="model" title="询价型号" data-index="model" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="suModel" title="商家型号" data-index="suModel" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="params" title="配置需求" data-index="params" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="suParams" title="商家参数" data-index="suParams" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="price" title="比价报价(¥)" data-index="price" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="finallyPrice" title="最终报价(¥)" data-index="finallyPrice" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="correctPrice" title="修正报价(¥)" data-index="correctPrice" align="center"/>
        <a-table-column :width="60" key="unit" title="单位" data-index="unit" align="center"/>
        <a-table-column :width="60" key="number" title="数量" data-index="number" align="center"/>
        <a-table-column :width="60" key="suPrice" title="供应商单价(¥)" data-index="suPrice" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="suDelivery" title="货期" data-index="suDelivery" align="center"/>
        <a-table-column :width="100" ellipsis="true" key="suRemark" title="商家备注" data-index="suRemark" align="center"/>
        <a-table-column :width="120" key="action" title="操作" align="center" fixed="right">
          <template slot-scope="t, r">
            <el-button @click="editPrice(r.id)" type="success" icon="el-icon-edit" size="mini" style="padding: 7px 10px;">修正</el-button>
          </template>
        </a-table-column>
        </a-table>
      </div>
    </el-card>
    </el-drawer>
  </div>
</template>
<script>
  import { getAction, postActionByJson, postActionByQueryString } from '@/api/manage'
  import '@/styles/auto-style.css'
  import { getUser } from '@/utils/auth'
  import { onFilterDropdownVisibleChange, onFilter, handleSearch, handleReset } from '@/utils/column-search'
  import elDragDialog from '@/directive/el-drag-dialog'
  import { dateTimeFormat } from '@/utils/format'
  import {CommonMixins} from "@/mixins/CommonMixins";

  export default {
    directives: { elDragDialog },
    mixins: [CommonMixins],
    data() {
      const scopedSlots = {
        filterDropdown: 'filterDropdown',
        filterIcon: 'filterIcon',
        customRender: 'customRender',
      }
      return {
        drawer: false,
        detailTable: {
          loading: false,
          data: [],
          pagination: {
            showTotal: total => `共 ${total} 条结果`,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            current: 1,
            pageSize: 10,
            total: 0,
            onChange: (item) => {
              this.detailTable.pagination.current = item
              this.loadPurchases()
            },
            onShowSizeChange: (current, pageSize) => {
              this.detailTable.pagination.pageSize = pageSize
              this.loadPurchases()
            }, // 改变每页数量时更新显示
          }
        },
        proTable: {
          loading: false,
          data: [],
          pagination: {
            showTotal: total => `共 ${total} 条结果`,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            current: 1,
            pageSize: 20,
            total: 0,
            onChange: (item) => {
              this.proTable.pagination.current = item
              this.toSearch()
            },
            onShowSizeChange: (current, pageSize) => {
              this.proTable.pagination.pageSize = pageSize
              this.toSearch()
            }, // 改变每页数量时更新显示
          }
        },
        userMap: {},

        filename: '',
        currentTemplate: {},
        searchForm: { time: []},
        downloadLoading: false,
        selectedRowKeys: [],

        purProjectsLoading: false,
        form: {},
        role: {},

        selectSupplier: null,

        scopedSlots,
        searchText: '',
        searchedColumn: '',
        searchInput: null,

        currentPro: '',
        selectKey: '',
        url: {
          inquiryResultFindPro: '/inquiry/inquiryResultFindPro',
          batchUpdatePrice: '/inquiry/batchUpdatePrice',
          findProPurchase: '/inquiry/findProPurchase',
          findProPurchaseAll: '/inquiry/findProPurchaseAll',
          findInquiryResult: '/inquiryResult/findInquiryResult',
          importInquiryResult: '/inquiryResult/importInquiryResult',
          cancelPurchase: '/inquiryResult/cancelPurchase'
        },
        //实时屏幕高度
        windowHeight: document.documentElement.clientHeight
      }
    },
    mounted() {
      window.onresize=()=>{
        return(()=>{
          window.fullHeight = document.documentElement.clientHeight;
          this.windowHeight = window.fullHeight;
        })()
      }
    },
    watch:{
      windowHeight(val){
        console.log("实时屏幕高度：",val, this.windowHeight );
      },
    },
    created() {
      this.role = this.$store.getters.roles[0]
      this.toSearch();
    },
    methods: {
      cancelPurchase(){
        if(this.selectedRowKeys.length != 0){
          postActionByQueryString(this.url.cancelPurchase, {quoteIds: this.selectedRowKeys})
          .then(resp =>{
            this.$message.success(resp.message + '条取消成功')
          })
        }
      },
      allChange(){
        //全选
        getAction('/inquiry/findProPurchaseAll', {proDetailId: this.searchForm.proDetailId})
        .then(resp => {
          this.selectedRowKeys = resp.data.map(item => { return item.quote.id });
        })
      },
      batchUpdatePrice(){
        if(this.selectedRowKeys.length == 0) {
          this.$message({
              type: 'info',
              message: '请选择要修改的行'
          })
        }else {
          this.$prompt('请输入公式参数', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              // inputPattern: /^[1-9][0-9]*([\.][0-9]{1,2})?$/,
              inputErrorMessage: '参数格式不正确'
          }).then(({ value }) => {
              postActionByQueryString(this.url.batchUpdatePrice, {quoteIds: this.selectedRowKeys, params: value})
              .then(resp => {
                this.$message({type: 'success',message: '更新成功'
                });
              }).catch(() => {
                this.$message({type: 'info',message: '更新失败'
                });
              }).finally(() => {
                this.loadPurchases()
              })
          }).catch(() => {
              this.$message({type: 'info',message: '取消输入'
              });
          });
        }
      },
      loadCurrentTemplate(id) {
        if (id) {
          getAction('/inquiry/template/findInquiryTemplate', {id: id})
          .then(resp => {
            resp.data[0].jsonKeys = JSON.parse(resp.data[0].jsonKeys)
            resp.data[0].tableColumn = JSON.parse(resp.data[0].tableColumn)
            this.currentTemplate = resp.data[0]
          })
          .catch(() => {
            this.loading = false
          })
        }
      },
      tableRowClassName(row, index){
        if(this.selectKey == row.id) {
          return 'selected'
        }else {
          return ''
        }
      },
      dateTimeFormat,
      rowClick(row, index) {
        return {
          on: {
            click: () => {
              this.searchForm.proDetailId = row.id
              this.currentPro = row.name
              this.filename = row.name + '-询价结果'
              this.selectKey = row.id
              this.loadPurchases()
              this.drawer = true
            }
          }
        }
      },
      toPurchase() {
        this.$confirm('是否确定发往采购，不可撤销，请谨慎操作', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          postActionByQueryString('/purchase/purchasePlan/inquiryResultSendPurchase', {
            ids: this.selectedRowKeys, operator: getUser()
          })
          .then(resp => {
            this.$message({ type: 'success', message: resp.message });
          }).catch(()=>{

          }).finally(()=>{
            this.loadPurchases()
            this.selectedRowKeys = []
          })
        })
      },
      editPrice(id) {
        this.$prompt('请输入修正报价', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[0-9][0-9]*([\.][0-9]{1,2})?$/,
          inputErrorMessage: '格式不正确'
        }).then(({ value }) => {
          let params = { id: id, correctPrice: value, operator: getUser() }
          postActionByQueryString('/inquiry/updateCorrectPrice', params)
          .then(resp => {
            this.$message({ message: resp.message, type: 'success' })
          })
        }).catch(() => {})
        .finally(()=>{
            this.loadPurchases()
        })
      },
      submitHandler() {

      },
      async handleDownload() {
        this.downloadLoading = true
        let data1 = []
        await getAction(this.url.importInquiryResult, {proId: this.searchForm.proDetailId})
        .then( resp =>{
          data1 = resp.data
        })
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['序号', '设备名称', '询价型号', '商家型号', '配置需求', '商家参数', '单位', '数量', '单价', '总价', '品牌', '货期', '备注',
            '设备位号', '仪表名字', '测量范围', '信号及规格', '连接方式', '保护管']
          const filterVal = ['sort', 'name', 'model', 'suModel', 'params', 'suParams', 'unit', 'number', 'price', 'totalPrice', 'brand', 'delivery', 'remark',
            'tagNumber', 'meter', 'measuringRange', 'meterSignal', 'connectionMode', 'tube']
          let list = []
          data1.map(item=>{
            if(this.selectedRowKeys.includes(item.quoteId)){
              list.push({
                sort: item.sort,
                name: item.name,
                model: item.model,
                suModel: item.suModel,
                params: item.params,
                suParams: item.suParams,
                unit: item.unit,
                number: item.number,
                price: item.correctPrice,
                totalPrice: Number(item.correctPrice * item.number).toFixed(2),
                brand: item.suBrand,
                delivery: item.suDelivery,
                remark: item.suRemark,
                tagNumber: item.tagNumber,
                meter: item.meter,
                measuringRange: item.measuringRange,
                meterSignal: item.meterSignal,
                connectionMode: item.connectionMode,
                tube: item.tube
              })
            }
          })
          if(list.length > 0){
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: this.filename
            })
            this.selectedRowKeys = []
          }else{
            this.$message.error('导出失败,无导出数据')
          }
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      onSelectChange(ids, rows) {

        if(ids.length == 0) {
          this.selectSupplier = null
        }
        this.selectedRowKeys = ids
      },
      toSearch() {
        this.proTable.loading = true
        postActionByQueryString(this.url.inquiryResultFindPro, {
          proName: this.searchForm.name,
          startTime: this.searchForm.time[0],
          overTime: this.searchForm.time[1],
          pageNum: this.proTable.pagination.current,
          pageSize: this.proTable.pagination.pageSize
        })
        .then( resp => {
          if (resp.data){
            this.proTable.data = resp.data.records
            this.proTable.pagination.current = parseInt(resp.data.current)
            this.proTable.pagination.pageSize = parseInt(resp.data.size)
            this.proTable.pagination.total = parseInt(resp.data.total)
          }else {
            this.$message.error('无数据');
          }
        }).catch(()=>{
          this.$message.error('查询失败');
        }).finally(()=>{
          this.proTable.loading = false
        })
      },
      loadPurchases(form) {
        this.detailTable.loading = true
        form = Object.assign({
          proId: this.searchForm.proDetailId,
          pageNum: this.detailTable.pagination.current,
          pageSize: this.detailTable.pagination.pageSize
        }, form)
        if(this.searchForm.proDetailId) {
          getAction(this.url.findInquiryResult, form)
          .then(response => {
            this.detailTable.data = response.data.records
            this.detailTable.pagination.current = response.data.current
            this.detailTable.pagination.pageSize = response.data.size
            this.detailTable.pagination.total = response.data.total
          }).catch(()=> {
            this.$message.error('查询失败')
          }).finally(()=>{
            this.detailTable.loading = false
          })
        }
      },
      onFilterDropdownVisibleChange,
      onFilter,
      handleReset,
      handleSearch,
    }
  }
</script>

<style lang="scss" scoped>
.inquiry-result {
  /deep/.el-form-item__content{
    height:auto;
    line-height:32px;
    margin-left:90px!important
  }
  .el-date-editor {
    border-color: #42B983;
  }
  /deep/.status-table {
    .selected {
      background: #e6f7ff;
    }
  }
}
</style>
